package com.gxsf.wechatbook.controller;

import com.gxsf.wechatbook.pojo.ReserList;
import com.gxsf.wechatbook.pojo.ReserUserInfo;
import com.gxsf.wechatbook.repo.ReserListRepository;
import com.gxsf.wechatbook.repo.ReserUserInfoRepository;
import com.gxsf.wechatbook.service.ReserService;
import com.gxsf.wechatbook.token.UserLoginToken;
import com.gxsf.wechatbook.util.Error;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author BeijiRonin
 * @version 1.0.0
 * @date 2021/1/21 18:47
 */
@RestController
@RequestMapping("/reser_json")
@CrossOrigin
@Slf4j
@Api(tags = "reser_json 预约管理")
public class ReserListController {
    @Autowired
    ReserListRepository reserListRepository;
    @Autowired
    ReserService reserService;
    @Autowired
    ReserUserInfoRepository reserUserInfoRepository;

    @ApiOperation("根据图书管ID查找图书管信息，需要携带token")
    @UserLoginToken
    @PostMapping("/list.json/{libraryId}")
    public List<ReserList> list(@PathVariable("libraryId") String libraryId) {
        return reserListRepository.findAllByLibraryId(Long.parseLong(libraryId));
    }

    @ApiOperation("预约")
    @UserLoginToken
    @PostMapping("/reser.json")
    public Object reser(@RequestBody() Map<String, String> map) {
        String userStr = map.get("user");
        String libraryStr = map.get("library");
        String reserStr = map.get("reser");
        return reserService.reser(userStr, libraryStr, reserStr);
    }

    //SELECT * FROM `reser_user_info` WHERE TO_DAYS(create_time) = TO_DAYS(NOW())
    @ApiOperation("退出预约")
    @UserLoginToken
    @PostMapping("/exit.opera/{userId}")
    public Object exit(@PathVariable("userId") long userId) {

        ReserUserInfo reserUserInfo = reserUserInfoRepository.findFirstByUserIdAndStatusOrderById(userId, 0);
        if (reserUserInfo == null) {
            return Error.error(500, "没有找到预约消息");
        }
        ReserList reserList = reserListRepository.findLibraryById(reserUserInfo.getLibraryId());
        //更新图书馆位置数量
        reserList.setNowPeople(reserList.getNowPeople() - 1);
        reserListRepository.save(reserList);
        reserUserInfo.setStatus(2);
        return reserUserInfoRepository.save(reserUserInfo);
    }
}
